package com.lamer.console.common.handle;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{username}")
@Component
public class WebSocketServer {

    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) throws IOException {
        sessionMap.put(username, session);
        System.out.println("连接成功: " + username);
        session.getBasicRemote().sendText(username + "连接websocket成功。");
    }

    @OnClose
    public void onClose(@PathParam("username") String username) {
        sessionMap.remove(username);
        System.out.println("连接关闭" + username);
    }

    @OnMessage
    public void onMessage(String message) {
        sendMessage(message);
    }

    private void sendMessage(String message) {
        sessionMap.forEach((key, value) -> {
            try {
                value.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
